<template>
    <div class="app-container">
        <div class="all">
            <div class="antv-content">
                <div class="antv-menu">
                    <div class="sc_listtitle">模型列表</div>
                    <ul class="menu-list">
                        <div class="sc_flexalign padding10">
                            <el-input v-model="inputName1" placeholder="请输入模型名称"></el-input>
                            <el-button class="marginleft20" @click="searchModel">查询</el-button>
                        </div>
                        <li class="sc_li" v-for="(item, ind) in nodeShapeList1" :key="ind" draggable="true"
                            @drag="menuDrag1(item.data.id)">
                            <strong>{{ item.label }}</strong>
                        </li>
                    </ul>

                    <Pagination v-bind:childMsg="modelListPageparm" @callFather="callFather1" ></Pagination>

                    <div class="sc_listtitle">数据集列表</div>
                    <ul class="menu-list">
                        <div class="sc_flexalign padding10">
                            <el-input v-model="inputName2" placeholder="请输入数据集名称"></el-input>
                            <el-button class="marginleft20" @click="searchDataList">查询</el-button>
                        </div>
                        <li class="sc_li" v-for="(item, ind) in nodeShapeList2" :key="ind" draggable="true"
                            @drag="menuDrag2(item.data.id)">
                            <strong>{{ item.label }}</strong>
                        </li>
                    </ul>

                    <Pagination v-bind:childMsg="dataListPageparm" @callFather="callFather2"></Pagination>
                    
                    <!-- <div class="wrapper-btn" v-if="isChange">
                        <el-button  @click="handlerSend">导出</el-button>
                        <el-button @click="handlerView">预览</el-button>
                    </div>
                    <div class="wrapper-btn">
                        <el-button @click="handlerTest">导入剪切板json数据</el-button>
                    </div>  
                    <div class="wrapper-btn">
                        <el-upload
                            :limit="1"
                            action=""
                            ref="upload"
                            accept=".json"
                            :on-change="handlerImp"
                        >
                            <el-button
                                class="el-icon-upload"
                                type="primary"
                            >
                            导入json文件
                            </el-button>
                        </el-upload>
                        
                    </div> -->


                </div>
                <div class="antv-wrapper">
                    <div class="wrapper-canvas" :style="{ height: height }" id="wrapper" @drop="drop($event)"
                        @dragover.prevent></div>
                    <div class="wrapper-tips">
                        <div class="wrapper-tips-item">
                            <el-switch v-model="isPortsShow" @change="changePortsShow"></el-switch>
                            <span class="sc_tipstext">链接桩常显</span>
                        </div>
                    </div>
                </div>
                <div v-if="editDrawer" class="edit-main">
                    <div class="edit-main-title">
                        <h3 class="sc_maintitletext">{{ editTitle }}</h3>
                        <i class="el-icon-close" @click="closeEditForm"></i>
                    </div>
                    <div v-if="editTitle === '组件详情（模型）'" class="form-main">
                        <!-- <el-form ref="nodeForm" :model="form" label-width="80px">
                            <el-form-item label="节点文本">
                                <el-input type="textarea" v-model="form.labelText" size="small"
                                    @input="changeNode('labelText', form.labelText)"></el-input>
                            </el-form-item>
                            <el-form-item label="节点层级">
                                <el-input v-model.number="form.zIndex" size="small"
                                    @input="changeNormalNode('zIndex', form.zIndex)"></el-input>
                            </el-form-item>
                            <el-form-item label="节点高度">
                                <el-input v-model.number="form.height" size="small"
                                    @input="changeNormalNode('height', form.height)"></el-input>
                            </el-form-item>
                            <el-form-item label="节点宽度">
                                <el-input v-model.number="form.width" size="small"
                                    @input="changeNormalNode('width', form.width)"></el-input>
                            </el-form-item>
                            <el-form-item label="字体大小">
                                <el-input v-model="form.fontSize" size="small"
                                    @input="changeNode('fontSize', form.fontSize)"></el-input>
                            </el-form-item>
                            <el-form-item label="字体颜色">
                                <el-color-picker v-model="form.fontFill"
                                    @change="changeNode('fontFill', form.fontFill)"></el-color-picker>
                            </el-form-item>
                            <el-form-item label="节点背景">
                                <el-color-picker v-model="form.fill"
                                    @change="changeNode('fill', form.fill)"></el-color-picker>
                            </el-form-item>
                            <el-form-item label="边框颜色">
                                <el-color-picker v-model="form.stroke"
                                    @change="changeNode('stroke', form.stroke)"></el-color-picker>
                            </el-form-item>
                        </el-form> -->
                        <el-form ref="nodeForm" :model="modeform" label-width="80px" >
                            <el-form-item label="模型名称">
                                <el-input disabled v-model="modeform.modelName" size="small"></el-input>
                            </el-form-item>
                            <el-form-item label="模型简介">
                                <el-input disabled v-model="modeform.modelDesc" size="small"></el-input>
                            </el-form-item>
                            <el-form-item label="模型路径">
                                <el-input disabled v-model="modeform.modelPath" size="small"></el-input>
                            </el-form-item>
                            <el-form-item label="模型标签">
                                <el-input disabled v-model="modeform.modelTagId" size="small"></el-input>
                            </el-form-item>
                            <el-form-item label="执行顺序">
                                <el-input v-model.number="modeform.zIndex" size="small"
                                    @input="changeNormalNode('zIndex', modeform.zIndex)"></el-input>
                            </el-form-item>
                        </el-form>
                    </div>
                    <div v-if="editTitle === '组件详情（数据集）'" class="form-main">
                        <el-form ref="nodeForm" label-position="top" :model="dataform" label-width="90px">
                            <el-form-item label="数据集名称">
                                <el-input disabled v-model="dataform.dataName" size="small"></el-input>
                            </el-form-item>
                            <el-form-item label="执行顺序">
                                <el-input v-model.number="dataform.zIndex" size="small"
                                    @input="changeNormalNode('zIndex', dataform.zIndex)"></el-input>
                            </el-form-item>
                            <el-form-item label="数据集简介">
                                <el-input type="textarea" :autosize="{ minRows: 2, maxRows: 8}" disabled v-model="dataform.dataDesc" size="small"></el-input>
                            </el-form-item>
                        </el-form>
                    </div>
                    <div v-if="editTitle === '编辑连线'" class="form-main">
                        <el-form ref="edgeForm" :model="form" label-width="80px">
                            <el-form-item label="标签内容">
                                <el-input v-model="form.label" size="small" placeholder="标签文字，空则没有" @input="
                                    changeEdgeLabel(
                                        form.label,
                                        labelForm.fontColor,
                                        labelForm.fill,
                                        labelForm.stroke
                                    )
                                    "></el-input>
                                <div v-if="form.label" class="label-style">
                                    <p class="sc_labelstylep">
                                        字体颜色：<el-color-picker v-model="labelForm.fontColor" size="mini" @change="
                                            changeEdgeLabel(
                                                form.label,
                                                labelForm.fontColor,
                                                labelForm.fill,
                                                labelForm.stroke
                                            )
                                            "></el-color-picker>
                                    </p>
                                    <p class="sc_labelstylep">
                                        背景颜色：<el-color-picker v-model="labelForm.fill" size="mini" @change="
                                            changeEdgeLabel(
                                                form.label,
                                                labelForm.fontColor,
                                                labelForm.fill,
                                                labelForm.stroke
                                            )
                                            "></el-color-picker>
                                    </p>
                                    <p class="sc_labelstylep">
                                        描边颜色：<el-color-picker v-model="labelForm.stroke" size="mini" @change="
                                            changeEdgeLabel(
                                                form.label,
                                                labelForm.fontColor,
                                                labelForm.fill,
                                                labelForm.stroke
                                            )
                                            "></el-color-picker>
                                    </p>
                                </div>
                            </el-form-item>
                            <el-form-item label="线条颜色">
                                <el-color-picker v-model="form.stroke" size="small"
                                    @change="changeEdgeStroke"></el-color-picker>
                            </el-form-item>
                            <el-form-item label="线条样式">
                                <el-select v-model="form.connector" size="small" placeholder="请选择"
                                    @change="changeEdgeConnector">
                                    <el-option label="直角" value="normal"></el-option>
                                    <el-option label="圆角" value="rounded"></el-option>
                                    <el-option label="平滑" value="smooth"></el-option>
                                    <el-option label="跳线(两线交叉)" value="jumpover"></el-option>
                                </el-select>
                            </el-form-item>
                            <el-form-item label="线条宽度">
                                <el-input-number v-model="form.strokeWidth" size="small" @change="changeEdgeStrokeWidth"
                                    :min="2" :step="2" :max="6" label="线条宽度"></el-input-number>
                            </el-form-item>
                            <el-form-item label="双向箭头">
                                <el-switch v-model="form.isArrows" @change="changeEdgeArrows"></el-switch>
                            </el-form-item>
                            <el-form-item label="流动线条">
                                <el-switch v-model="form.isAnit" @change="changeEdgeAnit"></el-switch>
                            </el-form-item>
                            <el-form-item label="调整线条">
                                <el-switch v-model="form.isTools" @change="changeEdgeTools"></el-switch>
                            </el-form-item>
                        </el-form>
                    </div>
                    <div class="edit-btn">
                        <el-button type="danger" @click="handlerDel" style="width: 100%">删除此{{ editTitle === "编辑连线" ? "连线" :
                            "节点" }}</el-button>
                    </div>
                </div>
                <div class="antv-menu-right">
                    <div class="sc_listtitle">模型实例名称<i class="el-input__icon el-icon-star-on" style="color: red;"></i></div>
                    <el-input v-model="modelConfigName" size="small"></el-input>
                    <!-- <el-input v-model="modelConfigName" size="small" placeholder="请输入算法配置名称">
                        <template #suffix>
                            <i class="el-input__icon el-icon-star-on" style="color: red;"></i>
                        </template>
                    </el-input> -->
                    <div class="sc_listtitle">模型实例简介<i class="el-input__icon el-icon-star-on" style="color: red;"></i></div>
                    <el-input  type="textarea" :autosize="{ minRows: 2, maxRows: 4}" v-model="modelConfigDesc" size="small"></el-input>
                    <!-- <el-input type="textarea" :autosize="{ minRows: 2, maxRows: 4}" v-model="modelConfigDesc" size="small" placeholder="请输入算法配置简介">
                        <template #suffix>
                            <i class="el-input__icon el-icon-star-on" style="color: red;"></i>
                        </template>
                    </el-input> -->
                    
                    
                    <div class="sc_listtitle">batchSize</div>
                    <el-input v-model="batchSize" size="small" placeholder="默认值为2"></el-input>
                    <div class="sc_listtitle">lr</div>
                    <el-input v-model="lr" size="small" placeholder="默认值为0.005">lr</el-input>
                    <div class="sc_listtitle" >epochs</div>
                    <el-input v-model="epochs" size="small" placeholder="默认值为10">epochs</el-input>
                </div>
            </div>
        </div>
        <LookDialog ref="LookDialog"></LookDialog>

    </div>
</template>
<script>
import { Transform } from "@antv/x6-plugin-transform";
import { Selection } from "@antv/x6-plugin-selection";
import { Snapline } from "@antv/x6-plugin-snapline";
import { Clipboard } from "@antv/x6-plugin-clipboard";
import { Keyboard } from "@antv/x6-plugin-keyboard";
import { History } from '@antv/x6-plugin-history'
import { Graph, Shape } from "@antv/x6";
import {
    configSetting,
    configNodeShape1,
    configNodeShape2,
    configNodePorts,
    configEdgeLabel,
    graphBindKey,
    // nodeShapeList1,
    nodeShapeList2,
} from "./utils/antvSetting";
import LookDialog from "./look-dialog.vue";
import Pagination from '@/components/Pagination'
import {
  ModelList,
  ModelDataList,
  ModelDataListByModelId,
} from '@/api/userMG'
// import FileSaver from 'file-saver'


export default {
    name: "",
    components: {
        LookDialog,
        Pagination,
    },
    props: {
        height: {
            type: String,
            default: "100%", //'720px'
        },
        value: {
            type: String,
            default: "",
        },
    },
    data() {
        return {
            graph: null,
            isChange: false,
            isPortsShow: false,
            menuItem1: "",
            menuItem2: "",
            selectCell: "",
            editDrawer: false,
            editTitle: "",
            form:{},
            modeform: {},
            dataform: {},
            labelForm: {
                fontColor: "#333",
                fill: "#FFF",
                stroke: "#555",
            },
            // editForm: {
            //     modelConfigName: '',
            //     modelConfigDesc: '',
            //     config:'',
            // },
            
            // 模型列表分页插件默认值
            modelListPageparm: {
                currentPage: 1,
                pageSize: 10,
                total: 10
            },
            // 数据集分页插件默认值
            dataListPageparm: {
                currentPage: 1,
                pageSize: 10,
                total: 10
            },
            // 发送分页请求时用到的参数
            modelListFormInline: {
                pageNum: 1,
                pageSize: 10,
                modelName:''
            },  

            dataListFormInline: {
                pageNum: 1,
                pageSize: 10,
                dataName:''
            },
            nodeShapeList1: [],
            nodeShapeList2: [],


            jsonData: "",
            inputName1: '',
            inputName2: '',
            modelConfigName: '',
            modelConfigDesc: '',
            batchSize: '',
            lr: '',
            epochs: '',
        };
    },
    created() {
        this.getModelListData(this.modelListFormInline)
        this.getDataListData(this.dataListFormInline)

     },
    // watch: {
    //     value: {
    //         handler: function () {
    //             if (this.graph) {
    //                 this.isChange = false;
    //                 this.isPortsShow = false;
    //                 this.menuItem1 = "";
    //                 this.menuItem2 = "";
    //                 this.selectCell = "";
    //                 this.editDrawer = false;
    //                 this.graph.dispose();
    //                 this.initGraph();
    //             }
    //         },
    //         deep: true,
    //         immediate: true,
    //     },
    // },
    mounted() {
        this.initGraph();

    },
    beforeDestroy() {
        this.graph.dispose();
    },
    methods: {
        searchModel(){
            this.modelListFormInline.modelName = this.inputName1
            this.getModelListData(this.modelListFormInline)

        },
        searchDataList(){
            this.dataListFormInline.dataName = this.inputName2
            this.getDataListData(this.dataListFormInline)
        },

        // 分页插件事件
        callFather1(parm) {
            this.modelListFormInline.pageNum = parm.currentPage
            this.modelListFormInline.pageSize = parm.pageSize
            this.modelListFormInline.modelConfigName = this.inputName1
            this.getModelListData(this.modelListFormInline)
        },
        // 分页插件事件
        callFather2(parm) {
            this.dataListFormInline.pageNum = parm.currentPage
            this.dataListFormInline.pageSize = parm.pageSize
            this.dataListFormInline.modelConfigName = typeof(this.formInline.algorithmName)==='undefined'?'':this.formInline.algorithmName
            this.getDataListData(this.dataListFormInline)
        },

        // 获取模型列表数据
        getModelListData(parameter){
            // console.log(parameter)
            ModelList(parameter).then(res => {
            if (res.code !== 200) {
                this.$message({
                type: 'info',
                message: res.msg
                })
            } 
            else {
                // 根据后端返回的数据动态生成数组
                // console.log(res.data.rows)
                this.nodeShapeList1 = res.data.rows.map((item) => {
                    // console.log(item)
                return {
                    attrs: {
                    label: {
                        text: item.modelName,
                        fontSize: 16,
                        fill: "#333",
                    },
                    body: {
                        fill: "#fff",
                        stroke: "#333",
                    },
                    },
                    data: {
                    id: item.id,
                    modelDesc:item.modelDesc,
                    modelPath:item.modelPath,
                    modelTagId:item.modelTagId
                    // url: item.url,
                    // reqType: item.reqType,
                    // reqParam: JSON.parse(item.reqParam),
                    },
                    height: 50,
                    width: 100,
                    shape: "rect",
                    label: item.modelName,
                };
                });
                // 分页赋值
                this.modelListPageparm.currentPage = res.data.page
                this.modelListPageparm.total = res.data.records

            }
        })
        .catch(err => {
          this.loading = false
          this.$message.error('获取模型列表失败，请稍后再试！'+err)
        })
        },

        // 获取数据集列表数据
        getDataListData(parameter){
            ModelDataList(parameter).then(res => {
            if (res.code !== 200) {
                this.$message({
                type: 'info',
                message: res.msg
                })
            } 
            else {  
                this.nodeShapeList2 = res.data.rows.map((item) => {
                return {
                    attrs: {
                        label: {
                            text: item.dataName,
                            fontSize: 16,
                            fill: "#333",
                        },
                        body: {
                            fill: "#fff",
                            stroke: "#333",
                        },
                    },
                    data: {
                        id: item.id,
                        dataDesc: item.dataDesc,
                        path: item.path,
                        type: item.type,
                    },
                    height: 75,
                    width: 150,
                    shape: "ellipse",
                    label: item.dataName,
                };
                });
                // 分页赋值
                this.dataListPageparm.currentPage = res.data.page
                this.dataListPageparm.total = res.data.records
                // this.nodeShapeList2 = res.data.rows

            }
        })
        .catch(err => {
          this.loading = false
          this.$message.error('获取数据集列表失败，请稍后再试！'+err)
        })
        },

        // 链接桩的显示与隐藏，主要是照顾菱形
        changePortsShow(val) {
            const container = document.getElementById("wrapper");
            const ports = container.querySelectorAll(".x6-port-body");
            for (let i = 0, len = ports.length; i < len; i = i + 1) {
                ports[i].style.visibility = val ? "visible" : "hidden";
            }
        },
        // 初始化渲染画布
        initGraph() {
            const graph = new Graph({
                container: document.getElementById("wrapper"),
                ...configSetting(Shape),
            });

            // 使用改变大小
            graph.use(
                new Transform({
                    resizing: {
                        enabled: true,
                        orthogonal: false
                    },
                })
            );

            // 使用可选择
            graph.use(
                new Selection({
                    enabled: true,
                    multiple: true,
                    rubberband: true,
                    movable: true,
                    showNodeSelectionBox: true,
                    // multipleSelectionModifiers: ['shift']
                })
            );

            // 使用对齐
            graph.use(
                new Snapline({
                    enabled: true,
                })
            );

            // 使用复制粘贴
            graph.use(
                new Clipboard({
                    enabled: true,
                })
            );

            // 使用快捷键
            graph.use(
                new Keyboard({
                    enabled: true,
                })
            );

            // 撤销重做
            graph.use(
                new History({
                    enabled: true,
                }),
            )
            // 画布事件
            graph.on("node:mouseenter", () => {
                this.changePortsShow(true);
            });
            graph.on("node:mouseleave", () => {
                if (this.isPortsShow) return;
                this.changePortsShow(false);
            });
            // 点击编辑
            graph.on("cell:click", ({ cell }) => {
                this.editForm(cell);
            });

            // 画布键盘事件
            graphBindKey(graph);
            // 删除
            graph.bindKey(["delete", "backspace"], () => {
                this.handlerDel();
            });
            // 赋值
            this.graph = graph;
            // 返现方法
            if (this.value && JSON.parse(this.value).length) {
                const resArr = JSON.parse(this.value);
                // 导出的时候删除了链接桩设置加回来
                const portsGroups = configNodePorts().groups;
                if (resArr.length) {
                    const jsonTemp = resArr.map((item) => {
                        if (item.ports) item.ports.groups = portsGroups;
                        return item;
                    });
                    graph.fromJSON(jsonTemp);
                }
            }
            // 画布有变化
            graph.on("cell:changed", () => {
                this.isChangeValue();
            });
        },
        // 画布是否有变动
        isChangeValue() {
            if (!this.isChange) {
                this.isChange = true;
                this.$emit("cellChanged", true);
            }
        },
        menuDrag1(id) {
            // this.menuItem1 = configNodeShape1(id);
            this.menuItem1 = this.nodeShapeList1.find(item => item.data.id === id)

            this.menuItem2 = ""
        },
        menuDrag2(id) {
            // this.menuItem2 = configNodeShape2(id);
            this.menuItem2 = this.nodeShapeList2.find(item => item.data.id === id)
            this.menuItem1 = ""
        },
        drop(event) {
            if (this.menuItem1) {
                const nodeItem1 = {
                    ...this.menuItem1,
                    x: event.offsetX - this.menuItem1.width / 2,
                    y: event.offsetY - this.menuItem1.height / 2,
                    ports: configNodePorts(),
                };
                // 创建节点
                this.graph.addNode(nodeItem1);
                this.isChangeValue();
            }
            if (this.menuItem2) {
                const nodeItem2 = {
                    ...this.menuItem2,
                    x: event.offsetX - this.menuItem2.width / 2,
                    y: event.offsetY - this.menuItem2.height / 2,
                    ports: configNodePorts(),
                };
                // 创建节点
                this.graph.addNode(nodeItem2);
                this.isChangeValue();
            }
        },
        //编辑
        editForm(cell) {
            console.log(cell.data)
            if (this.selectCell) this.selectCell.removeTools(); // 删除修改线的工具
            this.selectCell = cell;
            
            // 编辑模型节点

            // if (cell.isNode() && cell.data.type && cell.data.type.includes("mode") ) {
            if (cell.isNode() && cell.shape === "rect" ) {
                this.editTitle = "组件详情（模型）";
                console.log(cell.data.id)
                ModelDataListByModelId(cell.data.id).then(res =>{
                    
                    if (res.code !== 200) {
                        this.$message({
                        type: 'info',
                        message: res.msg
                })
            } 
            else {  
                this.nodeShapeList2 = res.data.map((item) => {
                return {
                    attrs: {
                        label: {
                            text: item.dataName,
                            fontSize: 16,
                            fill: "#333",
                        },
                        body: {
                            fill: "#fff",
                            stroke: "#333",
                        },
                    },
                    data: {
                        id: item.id,
                        dataDesc: item.dataDesc,
                        path: item.path,
                        type: item.type,
                    },
                    height: 75,
                    width: 150,
                    shape: "ellipse",
                    label: item.dataName,
                };
                });
                // 分页赋值
                this.dataListPageparm.currentPage = res.data.page
                this.dataListPageparm.total = res.data.records
                // this.nodeShapeList2 = res.data.rows

            }

                }).catch(err => {
                    this.$message.error('获取数据集列表失败，请稍后再试！'+err)
                })
                const body = cell.attrs.body || cell.attrs.rect || cell.attrs.polygon || cell.attrs.circle;
                // this.form = {
                //     labelText: cell.attrs.label.text || "",
                //     fontSize: cell.attrs.label.fontSize || 14,
                //     fontFill: cell.attrs.label.fill || "",
                //     fill: body.fill || "",
                //     stroke: body.stroke || "",
                //     zIndex: cell.getZIndex(),
                //     ...cell.size(),
                // };
                this.modeform = {
                    modelName: cell.attrs.label.text || "",
                    modelDesc: cell.data.modelDesc || '',
                    modelPath: cell.data.modelPath || '',
                    modelTagId: cell.data.modelTagId || '',
                    zIndex: cell.getZIndex(),
                    ...cell.size(),
                };
                
                return (this.editDrawer = true);
            }
            // 编辑数据集节点

            // if (cell.isNode() && cell.data.type && cell.data.type.includes("data") ) {
            if (cell.isNode() && cell.shape === "ellipse" ) {
                this.editTitle = "组件详情（数据集）";
                const body = cell.attrs.body || cell.attrs.rect || cell.attrs.polygon || cell.attrs.circle;
                this.dataform = {
                    dataName: cell.attrs.label.text || "",
                    dataDesc: cell.data.dataDesc || '',
                    zIndex: cell.getZIndex(),
                    ...cell.size(),
                };
                
                return (this.editDrawer = true);
            }

            // 编辑线
            if (!cell.isNode() && cell.shape === "edge") {
                this.editTitle = "编辑连线";
                this.form = {
                    label:
                        cell.labels && cell.labels[0]
                            ? cell.labels[0].attrs.labelText.text
                            : "",
                    stroke: cell.attrs.line.stroke || "",
                    connector: "rounded",
                    strokeWidth: cell.attrs.line.strokeWidth || "",
                    isArrows: cell.attrs.line.sourceMarker ? true : false,
                    isAnit: cell.attrs.line.strokeDasharray ? true : false,
                    isTools: false,
                };
                // 看是否有label
                const edgeCellLabel =
                    (cell.labels && cell.labels[0] && cell.labels[0].attrs) || false;
                if (this.form.label && edgeCellLabel) {
                    this.labelForm = {
                        fontColor: edgeCellLabel.labelText.fill || "#333",
                        fill: edgeCellLabel.labelBody.fill || "#fff",
                        stroke: edgeCellLabel.labelBody.stroke || "#555",
                    };
                } else {
                    this.labelForm = { fontColor: "#333", fill: "#FFF", stroke: "#555" };
                }
                return (this.editDrawer = true);
            }
        },
        closeEditForm() {
            this.editDrawer = false;
            if (this.selectCell) this.selectCell.removeTools();
        },
        changeNormalNode(type, value) {
            switch (type) {
                case "zIndex":
                    this.selectCell.setZIndex(value);
                    break;
                case "labelText":
                    this.selectCell.setData({ labelText: value });
                    break;
                case "height":
                    this.selectCell.resize(this.form.width, this.form.height);
                    break;
                case "width":
                    this.selectCell.resize(this.form.width, this.form.height);
                    break;
            }
        },
        // 修改按钮节点特殊属性
        changeBtnNode(type, value) {
            switch (type) {
                case "labelText":
                    this.selectCell.setData({ labelText: value });
                    break;
                case "btnType":
                    this.selectCell.setData({ btnType: value });
                    break;
            }
        },
        // 修改一般节点
        changeNode(type, value) {
            this.selectCell.setData({ someData: value });
            switch (type) {
                case "zIndex":
                    this.selectCell.setZIndex(value);
                    break;
                case "labelText":
                    this.selectCell.attr("label/text", value);
                    break;
                case "fontSize":
                    this.selectCell.attr("label/fontSize", value);
                    break;
                case "fontFill":
                    this.selectCell.attr("label/fill", value);
                    break;
                case "fill":
                    this.selectCell.attr("body/fill", value);
                    break;
                case "stroke":
                    this.selectCell.attr("body/stroke", value);
                    break;
            }
        },

        // 修改边label属性
        changeEdgeLabel(label, fontColor, fill, stroke) {
            this.selectCell.setLabels([
                configEdgeLabel(label, fontColor, fill, stroke),
            ]);
            if (!label)
                this.labelForm = { fontColor: "#333", fill: "#FFF", stroke: "#555" };
        },
        // 修改边的颜色
        changeEdgeStroke(val) {
            this.selectCell.attr("line/stroke", val);
        },
        // 边的样式
        changeEdgeConnector(val) {
            switch (val) {
                case "normal":
                    this.selectCell.setConnector(val);
                    break;
                case "smooth":
                    this.selectCell.setConnector(val);
                    break;
                case "rounded":
                    this.selectCell.setConnector(val, { radius: 20 });
                    break;
                case "jumpover":
                    this.selectCell.setConnector(val, { radius: 20 });
                    break;
            }
        },
        // 边的宽度
        changeEdgeStrokeWidth(val) {
            if (this.form.isArrows) {
                this.selectCell.attr({
                    line: {
                        strokeWidth: val,
                        sourceMarker: {
                            width: 12 * (val / 2) || 12,
                            height: 8 * (val / 2) || 8,
                        },
                        targetMarker: {
                            width: 12 * (val / 2) || 12,
                            height: 8 * (val / 2) || 8,
                        },
                    },
                });
            } else {
                this.selectCell.attr({
                    line: {
                        strokeWidth: val,
                        targetMarker: {
                            width: 12 * (val / 2) || 12,
                            height: 8 * (val / 2) || 8,
                        },
                    },
                });
            }
        },
        // 边的箭头
        changeEdgeArrows(val) {
            if (val) {
                this.selectCell.attr({
                    line: {
                        sourceMarker: {
                            name: "block",
                            width: 12 * (this.form.strokeWidth / 2) || 12,
                            height: 8 * (this.form.strokeWidth / 2) || 8,
                        },
                        targetMarker: {
                            name: "block",
                            width: 12 * (this.form.strokeWidth / 2) || 12,
                            height: 8 * (this.form.strokeWidth / 2) || 8,
                        },
                    },
                });
            } else {
                this.selectCell.attr({
                    line: {
                        sourceMarker: "",
                        targetMarker: {
                            name: "block",
                            size: 10 * (this.form.strokeWidth / 2) || 10,
                        },
                    },
                });
            }
        },
        // 边的添加蚂蚁线
        changeEdgeAnit(val) {
            if (val) {
                this.selectCell.attr({
                    line: {
                        strokeDasharray: 5,
                        style: {
                            animation: "ant-line 30s infinite linear",
                        },
                    },
                });
            } else {
                this.selectCell.attr({
                    line: {
                        strokeDasharray: 0,
                        style: {
                            animation: "",
                        },
                    },
                });
            }
        },
        // 给线添加调节工具
        changeEdgeTools(val) {
            if (val) this.selectCell.addTools(["vertices", "segments"]);
            else this.selectCell.removeTools();
        },
        // 删除节点
        handlerDel() {
            this.$confirm(
                `此操作将永久删除此${this.editTitle === "编辑连线" ? "连线" : "节点"
                }, 是否继续?`,
                "提示",
                {
                    confirmButtonText: "确定",
                    cancelButtonText: "取消",
                    type: "warning",
                }
            )
                .then(() => {
                    const cells = this.graph.getSelectedCells();
                    if (cells.length) {
                        this.graph.removeCells(cells);
                        this.form = {};
                        this.modeform = {};
                        this.dataform = {};
                        this.editDrawer = false;
                        this.$message({ type: "success", message: "删除成功!" });
                    }
                })
                .catch(() => { });
        },
        handlerView() {
            const { cells: jsonArr } = this.graph.toJSON();

            this.$refs.LookDialog.open(jsonArr)
        },
        // 导出
        handlerSend() {

            if(this.modelConfigName.trim() === '' || this.modelConfigDesc.trim() === '') {
                this.$message({
                    type: 'error',
                    message: '请完善模型实例信息'
            })
                return
            }
            if( this.lr.trim() === ''){
                this.lr = 0.005
            }
            if(this.batchSize.trim() === ''){
                this.batchSize = 2     
            }
            if(this.epochs.trim() === ''){
                this.epochs = 10
            }


            const { cells: jsonArr } = this.graph.toJSON();

            // console.log(this.graph.toJSON())



            // this.graph.fromJSON(this.graph.toJSON())
            if(jsonArr.length === 0) {
                this.$message({
                    type: 'error',
                    message: '请添加模型配置'
            })
                return
            }

            if (this.selectCell) {
                this.selectCell.removeTools();
                this.selectCell = "";
            }
            

            let data = []
            jsonArr.forEach(item=>{
                // console.log(item)
                if(item.shape === 'rect') {
                    data.push({
                        modelId:item.data.id,
                        sort:item.zIndex,

                        // id :item.data.id,
                        // sort:item.zIndex,
                        // type:item.data.type,
                    })
                }
                if(item.shape === 'ellipse') {
                    data.push({
                        dataId:item.data.id,
                        sort:item.zIndex,
                        // type:item.data.type,
                    })
                }
            })
            let jsonData = {
                modelConfigName:this.modelConfigName,
                modelConfigDesc:this.modelConfigDesc,
                batchSize:this.batchSize,
                lr:this.lr,
                epochs :this.epochs,
                data,
                // aaa:this.graph.toJSON()
            }
            // console.log(jsonData)
            this.$emit('jsonData',jsonData)
            // console.log(jsonData)
            this.graph.dispose();
            this.initGraph();
            this.modelConfigName = ''
            this.modelConfigDesc = ''
            this.batchSize = ''
            this.lr = ''
            this.epochs = ''

            // 保存本地文件
            // const blob = new Blob([JSON.stringify(jsonArr, null, 2)], { type: 'application/json' })
            // FileSaver.saveAs(blob, 'JSONData.json')

        },
        // 导入
        handlerImp(file) {
            let fileReader = new FileReader()
            fileReader.onload = async (e) => {
                try {
                    let document = JSON.parse(e.target.result)
                    const { cells: jsonArr } = this.graph.toJSON();
                    this.graph.fromJSON([...document, ...jsonArr])
                    this.graph.centerContent()
                    this.graph.zoomToFit()
                    this.isChangeValue();
                } catch (err) {
                    console.log(`load JSON document from file error: ${err.message}`)
                    this.$message.error(err.message || '错误操作');
                }
            }
            fileReader.readAsText(file.raw)

        },

        async handlerTest() {
            try {
                const { cells: jsonArr } = this.graph.toJSON();
                const text = await navigator.clipboard.readText();
                if (text.includes('[')) {
                    let arr = eval(text)
                    if (Array.isArray(arr)) {
                        this.graph.fromJSON([...arr, ...jsonArr])
                        this.graph.centerContent()
                        this.graph.zoomToFit()
                        this.isChangeValue();
                    } else {
                        throw '请粘贴正确的json数据'
                    }
                } else {
                    throw '请粘贴正确的json数据'
                }

            } catch (err) {
                this.$message.error(err || '错误操作');
            }
        }

    },

};
</script>
<style scoped="scoped">
@keyframes ant-line {
    to {
        stroke-dashoffset: -1000;
    }
}
</style>
<style scoped="scoped">
.all {
    border-radius: 8px;
    overflow: hidden;
    height: 100%;
    width: 100%;
}

.antv-content {
    background: #fff;
    display: flex;
    overflow: hidden;
    position: relative;
    height: 100%;
    width: 100%;


}

.antv-menu {
    width: 20%;
    /* width: 500px; */
    height: 800px;
    border-right: 1px solid #d5d5d5;
    padding: 10px;
    overflow: auto;
}
.antv-menu-right {
    width: 15%;
    /* width: 500px; */
    height: 500px;
    /* border-right: 1px solid #d5d5d5; */
    padding: 10px;
    overflow: auto;
    /* overflow:hidden; */
}

.sc_listtitle {
    padding: 10px;
    text-align: center;
    font-size: 18px;
    font-weight: bold;
    
}

.menu-list {
    border: 1px solid #000000;
    padding: 0;
    margin: 0;
}

.sc_li {
    padding: 10px;
    border-radius: 8px;
    border: 1px solid #555;
    background: #fff;
    margin: 5px 10px;
    font-size: 12px;
    display: flex;
    align-items: center;
    cursor: pointer;
    transition: all 0.5s ease;
    justify-content: center;
}

.sc_li:hover {
    box-shadow: 0 0 5px rgba(0, 0, 0, 0.3);
}

.antv-wrapper {
    flex: 1;
    position: relative;
}

.wrapper-canvas {
    position: relative;
    height: 100vh;
}

.wrapper-tips {
    padding: 10px;
    display: flex;
    align-items: center;
    position: absolute;
    top: 0;
    left: 0;


}

.sc_tipstext {
    padding-left: 10px;
    font-size: 12px;
}

i.icon-oval {
    display: inline-block;
    width: 16px;
    height: 10px;
    border-radius: 10px;
    border: 2px solid #555;
}

i.icon-square {
    display: inline-block;
    width: 16px;
    height: 10px;
    border: 2px solid #555;
}

i.icon-ysquare {
    display: inline-block;
    width: 16px;
    height: 10px;
    border-radius: 4px;
    border: 2px solid #555;
}

i.icon-rhombus {
    display: inline-block;
    width: 10px;
    height: 10px;
    border: 2px solid #555;
    transform: rotate(45deg);
}

i.icon-rhomboid {
    display: inline-block;
    width: 10px;
    height: 10px;
    border: 2px solid #555;
    transform: skew(-30deg);
}

i.icon-circle {
    display: inline-block;
    width: 16px;
    height: 16px;
    border-radius: 16px;
    border: 2px solid #555;
}

.edit-main {
    position:relative;
    right: 0;
    top: 0;
    height: 100%;
    width: 30%;
    border-left: 1px solid #f2f2f2;
    box-shadow: 0 -10px 10px rgba(0, 0, 0, 0.3);
    padding: 20px;
    /* padding-left: 20px; */
    /* padding: auto; */
    background: #fff;
    box-sizing: border-box;
}

.edit-main-title {
    display: flex;
    justify-content: space-between;
    align-items: center;
}

.sc_maintitletext {
    flex: 1;
}

.el-icon-close {
    cursor: pointer;
    font-size: 20px;
    opacity: 0.7;


}

.el-icon-close:hover {
    opacity: 1;
}

.form-main {
    padding: 20px 0;
    width: 100%;
    bottom: 0;
    /* position: fixed; */
    /* overflow:auto; */
    /* display:block; */
    /* position: absolute; */
    /* z-index: 9999;  */
}

.label-style {
    background: #f2f2f2;
    padding: 0 10px;
}

.sc_labelstylep {
    display: flex;
    align-items: center;
    font-size: 12px;
}



.wrapper-btn {
    width: 100%;
    display: flex;
    justify-content: space-around;
    margin-bottom: 10px;
}

.sc_flexalign {
    display: flex;
    align-items: center;
}

.padding10 {
    padding: 10px;
}

.marginleft20 {
    margin-left: 20px;
}</style>
